package com.cxh.rmsq.ui.fragment.self

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cxh.rmsq.R
import com.cxh.rmsq.db.model.CommunityContent
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource
import com.cxh.rmsq.net.RetrofitUtil
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.qrcode.SealQrCodeUISelector
import com.cxh.rmsq.ui.adapter.self.CircleListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.rong.imkit.RongIM

/**
 * 好友动态
 */
class FriendCommunityFragment : BaseFragment(), CircleListAdapter.OnCustomClickListener {

    private lateinit var refreshList: SmartRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private var page = 1
    private var listAdapter: CircleListAdapter? = null

    private val mContractViewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }
    private val imagesMediaList = java.util.ArrayList<LocalMedia>()

    override fun getLayoutResId(): Int {
        return R.layout.fragment_friend_community
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        refreshList = view.findViewById(R.id.refresh_list) as SmartRefreshLayout
        recyclerView = view.findViewById(R.id.rv_list) as RecyclerView


//        LinearLayoutManager mRecyclerViewLayoutManager2 = new LinearLayoutManager(getActivity());
//        mRecyclerViewLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(mRecyclerViewLayoutManager2);
        recyclerView.layoutManager = LinearLayoutManager(context)
        listAdapter = CircleListAdapter(3,this)
        listAdapter!!.setEmptyView(View.inflate(activity, R.layout.empty_data_layout, null))
        recyclerView.adapter = listAdapter
        listAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_like -> {
                    var type = 0
                    type = if (listAdapter!!.data[position].isLiked == 1) { //已点赞
                        0
                    } else {
                        1
                    }
                    val paramsMap = HashMap<String, Any>()
                    paramsMap["busId"] = listAdapter!!.data[position].id
                    paramsMap["userId"] = IMManager.getInstance().currentId
                    paramsMap["type"] = 1 //1动态2评论
                    paramsMap["isLiked"] = type //1:点赞 0：取消
                    paramsMap["bdzUserId"] = listAdapter!!.data[position].userId //被点赞用户id,
                    val body = RetrofitUtil.createJsonRequest(paramsMap)
                    mContractViewModel.commentLiked(paramsMap) {
                        if (it.code == 200) {
                            getData()
                        } else {
                            com.cxh.rmsq.utils.ToastUtils.showToast(it.msg);
                        }
                    }
//                    socialCircleViewModel.commentLiked(body)
//                    val finalType = type
//                    socialCircleViewModel.commentLiked()
//                        .observe(activity, object : Observer<Result2<String?>?> {
//                            fun onChanged(result: Result2<String?>) {
//                                if (result.code == 200) {
////                                    if (finalType ==1){
////                                        ToastUtils.showToast("点赞成功");
////                                    }
//                                    socialCircleViewModel.getCommunityPage(
//                                        IMManager.getInstance().currentId,  /*listAdapter.getData().get(position).getUserId() +*/
//                                        "",
//                                        page,
//                                        10
//                                    )
//                                }
//                            }
//                        })
                }
            }
        }

        refreshList.resetNoMoreData()
        refreshList.setRefreshHeader(MaterialHeader(activity))
        refreshList.setRefreshFooter(ClassicsFooter(activity))
        refreshList.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                getData()
                refreshLayout.finishLoadMore()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
//                dataList.clear()
                listAdapter!!.setNewInstance(null)
                getData()
            }
        })
    }

    override fun onResume() {
        super.onResume()
        page = 1
//        dataList.clear()
        listAdapter!!.setNewInstance(null)
        getData()
    }
    private fun getData(){
        mContractViewModel.getFriendShipsCommunityPage(IMManager.getInstance().getCurrentId(), page, 10){

            if (refreshList.isRefreshing) {
                refreshList.finishRefresh()
            }
            if (it.data != null ) {
                if (page == 1) {
                    listAdapter!!.setNewInstance(it.data.list)
                    if (it.data.list!!.size < 10) {
                        refreshList.setEnableLoadMore(false)
                    } else {
                        refreshList.setEnableLoadMore(true)
                    }
                } else {
                    if (it.data.list!!.size > 0) {
                        listAdapter!!.addData(it.data.list!!)
                        refreshList.setEnableLoadMore(true)
                    } else {
                        refreshList.setEnableLoadMore(false)
                        refreshList.finishLoadMoreWithNoMoreData()
                    }
                }
//                dataList.addAll(result.data.list)
//                Log.e("datalist.size", dataList.size.toString() + "")
                listAdapter!!.notifyDataSetChanged()
            }
        }
    }

    override fun onItemClick(position: Int, data: CommunityContent?) {
        var pos = 0
        imagesMediaList.clear()
        if (!TextUtils.isEmpty(data!!.files)) {
            if (data!!.files!!.contains(",")) { //多张
                for (i in MyUtils.toList(data!!.files).indices) {
                    val localMedia = LocalMedia()
                    localMedia.path = MyUtils.toList(data!!.files)[i]
                    imagesMediaList.add(localMedia)
                }
                pos = position
            } else {
                val localMedia = LocalMedia()
                localMedia.path = data!!.files
                imagesMediaList.add(localMedia)
                pos = 0
            }
        }
        PictureSelector.create(activity)
            .openPreview()
            .setImageEngine(GlideEngine.createGlideEngine())
            .isPreviewFullScreenMode(true)
//            .isPreviewZoomEffect(true, rlvCampClockImages)
            .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                override fun onPreviewDelete(position: Int) {

                }

                override fun onLongPressDownload(
                    context: Context,
                    media: LocalMedia
                ): Boolean {
                    return true
                }
            })
            .startActivityPreview(pos, false, imagesMediaList)
    }

    override fun onGroupClick(position: Int, data: CommunityContent?) {
        if (IMManager.getInstance().currentId == data!!.userId.toString()) {
            RongIM.getInstance()
                .startGroupChat(context, data!!.groupId.toString(), data!!.groupsName)
        } else {

            val uiSelector = SealQrCodeUISelector(requireContext())
            val result = MutableLiveData<Resource<String>>()

            uiSelector.checkIsInGroup(data!!.groupId.toString(), data!!.groupsName.toString(),result)
        }
    }


    override fun onItemLongClick(position: Int, data: CommunityContent?) {
        XPopup.Builder(activity)
            .dismissOnTouchOutside(true)
            .dismissOnBackPressed(true)
            .asBottomList(
                "", arrayOf("下载")
            ) { position, text ->
                if (data!!.pictureDownload == 1) {
                    if (data!!.fileType == 1) { //图片
                        if (!TextUtils.isEmpty(data!!.files)) {
                            if (data!!.files!!.contains(",")) { //多张
                                MyUtils.downloadImage(
                                    activity,
                                    MyUtils.toList(data!!.files)[position]
                                )
                            } else {
                                MyUtils.downloadImage(activity, data!!.files)
                            }
                        }
                    } else {
                        MyUtils.downloadFromNetwork(activity, data!!.files)
                    }
                } else {
                    com.cxh.rmsq.utils.ToastUtils.showToast("不允许下载！")
                }
            }.show()
    }
}